package top.dopen.home.work.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import springfox.documentation.annotations.ApiIgnore;
import top.dopen.home.work.common.AccessTokenTask;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Formatter;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *
 * </p>
 *
 * @Auther Dopen
 * @Date 2020/8/4
 */
@Api(value = "ExampleWechatController" ,tags = {"微信操作接口"})
@Slf4j
@RestController
@RequestMapping("/exam/qywechat")
public class ExampleWechatController {
	@Resource
	private AccessTokenTask accessTokenTask;
	@Value("${wechat.message.pushUrl}")
	private String pushMessageUrl ;
	@Value("${wechat.agentId}")
	private String agentId ;
	@Value("${wechat.corpid}")
	private String corpid;
	@Resource
	private RestTemplate template;

	/**
	 * 获取应用的accessToken
	 * @return
	 */
	@ApiOperation(value="获取应用的access token")
	@GetMapping("getAccessToken")
	public ResponseEntity<String> getAccessToken(){
		return new ResponseEntity<>(accessTokenTask.getAccessToken(), HttpStatus.OK);
	}

	/**
	 *推送应用消息
	 * @param userId
	 * @param content
	 * @return
	 */
	@ApiOperation(value="推送应用消息")
	@PostMapping("pushTextMessage")
	public ResponseEntity<String> pushTextMessage(@ApiParam(name = "userId",value = "成员企业微信账号（通讯录个人明细中查找）",required = true) String userId,
												  @ApiParam(name = "content",value = "推送文本消息内容",required = true) String content){

		if(StringUtils.isBlank(userId)||StringUtils.isBlank(content)){
			return new ResponseEntity<>("参数有误",HttpStatus.BAD_REQUEST);
		}
		JSONObject jsonObject = new JSONObject();
		JSONObject text = new JSONObject();
		jsonObject.put("touser",userId);
		jsonObject.put("msgtype","text");
		jsonObject.put("agentid",agentId);
		text.put("content",content);
		jsonObject.put("text",text);
		log.info("发送消息内容：{}",jsonObject.toJSONString());
		String accessToken = accessTokenTask.getAccessToken();
		String url = pushMessageUrl.replace("ACCESS_TOKEN", accessToken);
		HttpHeaders headers = new HttpHeaders();
		headers.setContentType(MediaType.APPLICATION_JSON);
		HttpEntity<String> requestEntity = new HttpEntity<>(jsonObject.toJSONString(),headers);
		String s = template.postForObject(url, requestEntity, String.class);
		JSONObject response = JSON.parseObject(s);
		if("ok".equalsIgnoreCase(response.getString("errmsg"))){
			return new ResponseEntity<>("success",HttpStatus.OK);
		}else{
			return new ResponseEntity<>(response.getString("errmsg"),HttpStatus.INTERNAL_SERVER_ERROR);
		}

	}

	/**
	 * js认证提供效验参数
	 * @param from
	 * @return
	 */
	@ApiIgnore
	@PostMapping("/getParam")
	public ResponseEntity<Map<String,String>> getParam(String from){
		if(org.springframework.util.StringUtils.isEmpty(from)){
			return null;
		}
		Map<String, String> sign = SignUtil.sign(accessTokenTask.getJsapiTicket(), from);
		sign.put("appId",corpid);
		return new ResponseEntity<>(sign,HttpStatus.OK);

	}

	/**
	 * 微信签名工具类
	 */
	static class SignUtil{
		/***
		 * 获取界面调用jsapi的所需参数
		 * @param jsapi_ticket 凭据
		 * @param url 界面请求地址
		 * @return 必要四个参数
		 */
		public static Map<String, String> sign(String jsapi_ticket, String url) {
			Map<String, String> ret = new HashMap<String, String>();
			String nonce_str = create_nonce_str();
			Long timestamp = create_timestamp();
			String string1;
			String signature = "";
			//System.out.println("");
			//注意这里参数名必须全部小写，且必须有序
			string1 = "jsapi_ticket=" + jsapi_ticket +
					"&noncestr=" + nonce_str +
					"&timestamp=" + timestamp +
					"&url=" + url;

			try{
				MessageDigest crypt = MessageDigest.getInstance("SHA-1");
				crypt.reset();
				crypt.update(string1.getBytes("UTF-8"));
				signature = byteToHex(crypt.digest());
			}catch (NoSuchAlgorithmException e){
				e.printStackTrace();
			}catch (UnsupportedEncodingException e){
				e.printStackTrace();
			}
			ret.put("url", url);
			ret.put("jsapi_ticket", jsapi_ticket);
			ret.put("nonceStr", nonce_str);
			ret.put("timestamp", timestamp.toString());
			ret.put("signature", signature);
			log.info("string1:{}",string1);
			log.info("url:{}", url);
			log.info("jsapi_ticket:{}", jsapi_ticket);
			log.info("nonceStr:{}", nonce_str);
			log.info("timestamp:{}", timestamp.toString());
			log.info("signature:{}", signature);

			return ret;
		}

		private static String byteToHex(final byte[] hash) {
			Formatter formatter = new Formatter();
			for (byte b : hash)
			{
				formatter.format("%02x", b);
			}
			String result = formatter.toString();
			formatter.close();
			return result;
		}

		private static String create_nonce_str() {
			//return UUID.randomUUID().toString().replace("-","");
			return "dfasf5ew14adf4er2t1546asdf4";
		}

		private static long create_timestamp() {
			return System.currentTimeMillis();
			//return Long.toString(System.currentTimeMillis() / 1000);
		}

	}
}
